package cn.com.smart.module.tool.log.util;

import com.lmax.disruptor.RingBuffer;
import com.lmax.disruptor.dsl.Disruptor;
import cn.com.smart.module.tool.log.domain.LoggerMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


/**
 * Content :Disruptor 环形队列
 */
@Component
public class LoggerDisruptorQueue {

	private LoggerEventRunnableFactory thFactory = new LoggerEventRunnableFactory();

    // The factory for the event
    private LoggerEventFactory factory = new LoggerEventFactory();

    // Specify the size of the ring buffer, must be power of 2.
    private int bufferSize = 2 * 1024;

    // Construct the Disruptor
    private Disruptor<LoggerEvent> disruptor = new Disruptor<>(factory, bufferSize, thFactory);


    private static  RingBuffer<LoggerEvent> ringBuffer;



    @Autowired
    LoggerDisruptorQueue(LoggerEventHandler eventHandler) {
        disruptor.handleEventsWith(eventHandler);
        this.ringBuffer = disruptor.getRingBuffer();
        disruptor.start();

    }

    public static void publishEvent(LoggerMessage log) {
        long sequence = ringBuffer.next();  // Grab the next sequence
        try {
            LoggerEvent event = ringBuffer.get(sequence); // Get the entry in the Disruptor
            // for the sequence
            event.setLog(log);  // Fill with data
        } finally {
            ringBuffer.publish(sequence);
        }
    }



}